import axios from '@/utils/request'
const ORDER_STATUS = {
  '-2': '支付失败',
  '-1': '已取消',
  1: '已提交',
  2: '已成交',
  3: '已发货',
  4: '已结算',
  5: '已完成'
}
const STATUS_COLOR = {
  '-2': 'danger',
  '-1': 'info',
  1: 'primary',
  2: 'warning',
  3: 'warning',
  4: 'success',
  5: 'success'
}

export default {
  OfficerOrderItem: {
    entity: { name: 'OrderItem', prefix: `officer` },
    form: {
      fields: [
        'id'
      ]
    },
    list: {
      export: {
        query: {
          '@display': `{
            'id' : 'entity.getId()',
            'createdTime' : 'entity.getCreatedTime().format("Y-m-d H:i:s")',
            'counter' : 'entity.getOrder().getCounter().__toString()',
            'staff' : 'entity.getOrder().getStaff().__toString()',
            'squad' : 'entity.getOrder().getSquad().__toString()',
            'leader' : 'entity.getOrder().getLeader().__toString()',
            'broker' : 'entity.getOrder().getBroker().__toString()',
            'item' : 'entity.__toString()',
            'status' : '{ "-2": "支付失败", "-1": "已取消", 1: "已提交", 2: "已支付", 3: "已发货", 4: "已结算", 5: "已完成" }[entity.getOrder().getStatus()]',
            'price' : 'entity.getPrice()',
            'totalPrice' : 'entity.getOrder().getTotalPrice()',
            'laterPay': 'entity.getOrder().getLaterPay() ? "待结账" : "已结账"'
          }`,
          limit: 10000000
        },
        label: {
          'id': 'id',
          'createdTime': '创建时间',
          'counter': '台号',
          'staff': '业务',
          'squad': '小队',
          'leader': '队长',
          'broker': '经纪人',
          'item': '项目',
          'status': '状态',
          'price': '金额',
          'totalPrice': '订单总价',
          'laterPay': '支付状态'
        }
      },
      disabled_actions: ['new', 'delete', 'edit'],
      actions: [
        {
          name: 'button',
          position: 'list',
          component: {
            props: ['record', 'refresh'],
            data() {
              return {
                loading: false
              }
            },
            render(h) {
              if (parseInt(this.record.order.__metadata.status) === 4) {
                return (
                  <el-popconfirm title='确定反结算当前订单？'
                    {...{
                      on: {
                        onConfirm: (val) => {
                          this.loading = true
                          axios.post(`/officer/orders/${this.record.order.id}/settle-remove`).then((res) => {
                            this.$message.success('执行成功！')
                            this.refresh()
                          }).finally(() => {
                            this.loading = false
                          })
                        }
                      }
                    }}>
                    <el-button slot='reference' size='small' type='warning' icon='el-icon-delete' loading={this.loading} plain>反结算</el-button>
                  </el-popconfirm>
                )
              } else if (this.record.order.__metadata.laterPay === false && parseInt(this.record.order.__metadata.status) >= 2 && parseInt(this.record.order.__metadata.status) <= 3) {
                return (
                  <el-popconfirm title='确定结算当前订单？'
                    {...{
                      on: {
                        onConfirm: (val) => {
                          this.loading = true
                          axios.post(`/officer/orders/${this.record.order.id}/settle-generate`).then((res) => {
                            this.$message.success('执行成功！')
                            this.refresh()
                          }).finally(() => {
                            this.loading = false
                          })
                        }
                      }
                    }}>
                    <el-button slot='reference' size='small' type='success' icon='el-icon-delete' loading={this.loading} plain>结算</el-button>
                  </el-popconfirm>
                )
              } else if (this.record.order.__metadata.laterPay === true && parseInt(this.record.order.__metadata.status) <= 2 && parseInt(this.record.order.__metadata.invoice.__metadata.status) === 0) {
                return (
                  <el-popconfirm title='确定取消当前订单？'
                    {...{
                      on: {
                        onConfirm: (val) => {
                          this.loading = true
                          axios.put(`/officer/orders/${this.record.order.id}`, { status: -1 }).then((res) => {
                            this.$message.success('执行成功！')
                            this.refresh()
                          }).finally(() => {
                            this.loading = false
                          })
                        }
                      }
                    }}>
                    <el-button slot='reference' size='small' type='info' icon='el-icon-delete' loading={this.loading} plain>取消订单</el-button>
                  </el-popconfirm>
                )
              }
            }
          }
        }
      ],
      query: {
        '@filter': 'entity.getOrder().getStatus() >= 2',
        '@order': 'entity.id|DESC',
        '@expands': "['entity.order.invoice']"
      },
      list_filter: {
        'order.status': Object.assign({ __label: '订单状态' }, ORDER_STATUS),
        'order.laterPay': Object.assign({ __label: '支付状态' }, { 0: '已结账', 1: '待结账' }),
        'order.invoice.status': Object.assign({ __label: '收款状态' }, { 0: '待支付', 1: '已支付', '-2': '待生成' }),
        beforeCreatedTime: {
          expression: 'entity.getCreatedTime() >= datetime.get(":value 08:00:00")',
          label: '下单开始时间',
          type: 'date'
        },
        afterCreatedTime: {
          expression: 'entity.getCreatedTime() < datetime.get(":value 07:59:59")',
          label: '下单结束时间',
          type: 'date'
        },
        'counter': {
          expression: 'entity.getOrder().getCounter().getId() == ":value"',
          label: '台号',
          type: 'remote-select',
          data: [],
          remoteMethod: (query, context) => {
            axios
              .get(`/officer/counters`, { params: {
                '@filter': `entity.getName() matches "${query}"`,
                '@order': `entity.listOrder|ASC,entity.id|DESC`
              }})
              .then(res => {
                context.data = res.data.map(v => { return { value: v.id, label: v.name } })
              })
          }
        },
        'order.squad.id': () => {
          return axios
            .get(`/officer/squads`)
            .then(res =>
              Object.assign({ __label: '小队' },
                ...res.data.map(v => { return { [v.id]: v.name } })))
        },
        'staff': {
          expression: 'entity.getOrder().getStaff().getId() == ":value"',
          label: '业务员/工号',
          type: 'remote-select',
          data: [],
          remoteMethod: (query, context) => {
            axios
              .get(`/officer/staffs`, { params: { '@filter': `entity.getName() matches "${query}" || entity.getId() matches "${query}"` }})
              .then(res => {
                context.data = res.data.map(v => { return { value: v.id, label: v.id + v.name } })
              })
          }
        },
        'specification.id': () => {
          return axios
            .get(`/officer/specifications`, {
              params: {
                '@order': `entity.listOrder|ASC`
              }
            })
            .then(res =>
              Object.assign({ __label: '产品' },
                ...res.data.map(v => { return { [v.id]: v.name } })))
        }
      },
      list_display: [
        'id',
        'createdTime',
        { property: 'order.__metadata.counter.__toString', label: '台号' },
        { property: 'order.__metadata.staff.__toString', label: '业务' },
        { property: 'order.__metadata.squad.__toString', label: '所属小队' },
        { property: 'order.__metadata.leader.__toString', label: '队长' },
        { property: 'order.__metadata.broker.__toString', label: '经纪人' },
        {
          property: '__toString',
          label: '项目',
          component: {
            props: ['data'],
            render(h) {
              return <el-tag>{this.data}</el-tag>
            }
          }
        },
        {
          property: 'order.__metadata.status',
          label: '订单状态',
          component: {
            props: ['data'],
            data() {
              return {
                status: ORDER_STATUS,
                color: STATUS_COLOR
              }
            },
            render(h) {
              return <el-tag type={this.color[this.data]} effect='plain'>{this.status[this.data]}</el-tag>
            }
          }
        },
        { property: 'price', label: '金额' },
        { property: 'order.__metadata.totalPrice', label: '订单总价' },
        {
          property: 'order.__metadata.laterPay', label: '支付状态',
          component: {
            props: ['data'],
            render(h) {
              if (this.data) {
                return <el-tag>待结账</el-tag>
              } else {
                return <el-tag type='success'>已结账</el-tag>
              }
            }
          }
        },
        {
          property: 'order.__metadata.invoice.__metadata.status', label: '收款状态',
          component: {
            props: ['data'],
            render(h) {
              if (this.data === 0) {
                return <el-tag>未支付</el-tag>
              } else if (this.data === -2) {
                return <el-tag type='info'>待生成</el-tag>
              } else if (this.data === 1) {
                return <el-tag type='success'>已支付</el-tag>
              }
            }
          }
        }
      ]
    }
  }
}
